package core.service
{
import core.Configuration;
import core.service.adapter.DataAdapterMap;
import core.service.adapter.IDataAdapter;

import mx.utils.UIDUtil;

public class ServiceRequest
{
    public function ServiceRequest(method:String, 
														   params:Array = null, 
							                               onResponse:Function = null,
							                               onError:Function = null,
														   useAdapter:Boolean = true,
														   returnResponse:Boolean = false)
    {
        super();
        
        this.method = Configuration.getService(method);
        if (params && params.length > 0) this.params = params;
        this.onResponse = onResponse;
        this.onError = onError;
		
		if (useAdapter)
		{
			this.adapter = DataAdapterMap.getAdapter(method);
		}
		
		this.returnResponse = returnResponse;
    }
	
	private var _uid:String = UIDUtil.createUID();
	
	public function get uid():String
	{
		return _uid;
	}
	
	public var index:int = 0;
    
    public var method:String;
    
    public var params:Array = [];
    
    public var onResponse:Function;
    
    public var onError:Function;
	
	public var adapter:IDataAdapter;
	
	public var returnResponse:Boolean = false;
    
    private var _response:SuccessResponse;

	public function get response():SuccessResponse
	{
		return _response;
	}

	public function set response(value:SuccessResponse):void
	{
		_response = value;
		_response.service_ns::request = this;
	}
    
    private var _error:ErrorResponse;

	public function get error():ErrorResponse
	{
		return _error;
	}

	public function set error(value:ErrorResponse):void
	{
		_error = value;
		_error.service_ns::request = this;
	}
    
    private var _isCompleted:Boolean = false;

    public function get isCompleted():Boolean
    {
        return _isCompleted;
    }
	
	public function addParam(...args):void
	{
		for (var i:int = 0; i < args.length; i++)
		{
			params.push(args[i]);
		}
	}
	
	public function get gameRequestParamFormat():Array
	{
		var temp:Array = [ method ];
		if (params && params.length > 0) temp = temp.concat(params);
		return temp;
	}
    
    public function complete():void
    {
        _isCompleted = true;
		
		if (error && onError != null) 
		{
			onError(error);
		}
		else
		{
			if (response && onResponse != null)
			{				
				if (returnResponse)
				{
					onResponse(response);
					return;
				}
				
				var data:Object = response.data;
				
				if (adapter != null)
				{
					data = adapter.parse(response.data);
				}
				
				onResponse(data);
			}
		}
    }
}
}


